<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <user-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        cache-key="systemUserTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit()"
          >
            新建
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="removeBatch"
          >
            删除
          </el-button>
        </template>
        <!-- 用户名列 -->
        <template v-slot:nickname="{ row }">
          <router-link :to="'/system/user/details?id=' + row.userId">
            {{ row.nickname }}
          </router-link>
        </template>
        <!-- 角色列 -->
        <template v-slot:roles="{ row }">
          <el-tag
            v-for="item in row.roles"
            :key="item.roleId"
            size="mini"
            type="primary"
            :disable-transitions="true"
          >
            {{ item.roleName }}
          </el-tag>
        </template>
        <!-- 状态列 -->
        <template v-slot:status="{ row }">
          <el-switch
            :active-value="2"
            :inactive-value="1"
            v-model="row.status"
            @change="editStatus(row)"
          />
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            style="color: #0066CC"
            icon="el-icon-edit"
            @click="openEdit(row)"
          >
            修改
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-coin"
            style="color: #CC3399"
            @click="openTransfer(row)"
          >
            充值点数
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-_usd"
            style="color: #003399"
            @click="moneyEdit(row)"
          >
            充值余额
          </el-link>
          <!--<el-dropdown placement="bottom" trigger="click">
            <el-link
              type="warning"
              :underline="false"
              icon="el-icon-set-up"
              style="color: #FFCC33"
            >
              更多
            </el-link>
            <template v-slot:dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click.native="addBusiness(row)">添加商家</el-dropdown-item>
                <el-dropdown-item @click.native="checkBusiness(row)">查看商家</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>-->
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-set-up"
            style="color: #FFCC33"
            @click="checkBusiness(row)"
          >
            查看商家
          </el-link>
          <!--<el-link
            type="primary"
            :underline="false"
            icon="el-icon-set-up"
            style="color: #FFCC33"
            @click="addBusiness(row)"
          >
            添加商家
          </el-link>-->
          <el-popconfirm
            class="ele-action"
            title="确定要重置密码此代理吗？ 重置密码默认为'123456'"
            @confirm="resets(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" style="color: #009966" :underline="false" icon="el-icon-refresh">
                重置密码
              </el-link>
            </template>
          </el-popconfirm>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此代理吗？"
            @confirm="remove(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- ‘添加商家’弹窗 -->
    <add-merchant ref="edit" :visible.sync="merchantEdit" :data="current" @done="reload" />
    <!--充值余额-->
    <money-edit :visible.sync="moneyView" :data="current" @done="reload" />
    <!--打开查询商家-->
    <check-business ref="business" :visible.sync="checkView" @done="reload" />
    <!-- 编辑弹窗/新建代理 -->
    <user-edit :typeList="typeList" :visible.sync="showEdit" :data="current" @done="reload" />
    <!-- 充值点数 弹窗 -->
    <equipment-edit :visible.sync="showTransfer" :data="current" @done="reload" />
    <!-- 导入弹窗 -->
    <user-import :visible.sync="showImport" @done="reload" />
  </div>
</template>

<script>
  import addMerchant from './components/add-merchant.vue';
  import UserSearch from './components/user-search.vue';
  import CheckBusiness from './components/check-business.vue';
  import UserEdit from './components/user-edit.vue';
  import moneyEdit from './components/money-edit.vue';
  import UserImport from './components/user-import.vue';
  import EquipmentEdit from './components/equipment-edit.vue';
  import {
    pageMerchant,
    removeAgent,
    updateUserStatus,
    resetPassword,
    updateUserPassword, pageAgencyType
  } from '@/api/oem';
  import {JSEncrypt} from "jsencrypt";

  export default {
    name: 'SystemUser',
    components: {
      addMerchant,
      UserSearch,
      EquipmentEdit,
      UserEdit,
      moneyEdit,
      CheckBusiness,
      UserImport
    },
    data() {
      return {
        // 表格列配置
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            type: 'index',
            label: '序号',
            width: 60,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'oemCode',
            label: '代理账号',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'balance',
            label: '余额',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'counts'
          },
          {
            prop: 'counts',
            label: '点数',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'counts'
          },
          {
            prop: 'platformDetails',
            label: '平台信息',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'linkman',
            label: '联系人',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'phone',
            label: '联系电话',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'status',
            label: '是否冻结',
            align: 'center',
            sortable: 'custom',
            width: 115,
            resizable: false,
            slot: 'status',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (_row, _column, cellValue) => {
              return this.$util.toDateString(cellValue);
            }
          },
          {
            prop: 'expirationTime',
            label: '到期时间',
            sortable: 'custom',
            align:'center',
            showOverflowTooltip: true,
            minWidth: 150
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 500,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed:'right'
          }
        ],
        // 表格选中数据
        selection: [],
        // 当前编辑数据
        current: null,
        // 是否显示‘添加商家’弹框
        merchantEdit:false,
        // 是否显示编辑弹窗
        showEdit: false,
        // 是否显示导入弹窗
        showImport: false,
        //是否显示充值编辑弹窗
        showTransfer: false,
        /*打开编辑查看商家*/
        checkView: false,
        moneyView: false,

        // 代理类型list
        typeList:[],
      };
    },
    // 路由刷新
    activated(){
      this.init()
    },
    created(){
    },
    methods: {
      // 查询代理类型
      init(){
        pageAgencyType({
          deleted:0,
          limit:10,
          page:1,
          types:2,
          oemId:this.$store.state.user.info.oemId   //代理id
        })
          .then((data) => {
            this.typeList=data.list
            console.log("data==",data)
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        if (!where.deleted) where.deleted
        return pageMerchant(
        { ...where, ...order, page, limit, oemType:2,parentId:this.$store.state.user.info.oemId
        }
        );
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },
      /* 打开编辑弹窗 */
      openEdit(row) {
        this.current = row;
        this.showEdit = true;
      },
      /* 打开充值编辑弹窗 */
      openTransfer(row) {
        this.current = row;
        this.showTransfer = true;
      },
      /*添加商家*/
      addBusiness(row){
        this.current = row;
        this.merchantEdit = true;
        console.log("row===",row)
        // show事件传值:row
        // this.$refs['edit'].show(row)
      },
      /*查看商家*/
      checkBusiness(row){
        this.current = row;
        console.log("this.current",this.current)
        this.checkView = true;
        this.$refs['business'].init(row)
      },
      /*充值余额*/
      moneyEdit(row){
        this.current = row;
        this.moneyView = true;
      },

      /* 打开导入弹窗 */
      openImport() {
        this.showImport = true;
      },
      /* 删除 */
      remove(row) {
        const loading = this.$loading({ lock: true });
        removeAgent({ids:[row.id]})
          .then((msg) => {
            loading.close();
            this.$message.success(msg);
            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      /*重置密码*/
      resets(row){
        const loading = this.$loading({ lock: true });
         console.log("row", row);
        let encryptor = new JSEncrypt()
        let pk = this.$store.state.signature.pk
        encryptor.setPublicKey(pk)
        // 密码加密
        let oemPassword = encryptor.encrypt('123456')

        resetPassword({
          // userId:this.$store.state.user.info.userId,
          // username:this.$store.state.user.info.username,// 用户名称
          // oemCode:row.oemCode, //oem账号
          // phone:row.phone, //手机号
          id:row.id, //oemId
          oemPassword:oemPassword //密码
        })
          .then((msg) => {
            loading.close();
            this.$message.success('密码重置成功！');
            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      /* 批量删除 */
      removeBatch() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$confirm('确定要删除选中的代理吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            const loading = this.$loading({ lock: true });
            removeAgent({ids: this.selection.map((d) => d.id)})
              .then((msg) => {
                loading.close();
                this.$message.success(msg);
                this.reload();
              })
              .catch((e) => {
                loading.close();
                this.$message.error(e.message);
              });
          })
          .catch(() => {});
      },
      /* 更改状态 */
      editStatus(row) {
        const loading = this.$loading({ lock: true });
        updateUserStatus(row.id, row.status)
          .then((msg) => {
            loading.close();
            this.$message.success( row.status==1?'启用成功！' :'冻结成功！');
          })
          .catch((e) => {
            loading.close();
            row.status = !row.status ? 1 : 0;
            this.$message.error(e.message);
          });
      }
    }
  };
</script>
